import { useState, useEffect } from 'react';
import { messageApi, Message, CreateMessageRequest, MessageListQuery } from '@/lib/api/message';

export function useMessages(sessionId: string, query: MessageListQuery = {}) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);

  const fetchMessages = async () => {
    if (!sessionId) return;
    
    try {
      setLoading(true);
      setError(null);
      const response = await messageApi.getSessionMessages(sessionId, query);
      setMessages(response.items);
      setTotal(response.total);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to get messages');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMessages();
  }, [sessionId, query.page, query.pageSize, query.order]);

  const sendMessage = async (content: string, metadata?: any) => {
    try {
      const response = await messageApi.createMessage({
        content,
        sessionId,
        metadata,
      });
      
      // Add new message to list
      setMessages(prev => [...prev, response.userMessage, response.aiResponse]);
      setTotal(prev => prev + 2);
      
      return response;
    } catch (err: any) {
      throw new Error(err.response?.data?.message || 'Failed to send message');
    }
  };

  return {
    messages,
    loading,
    error,
    total,
    sendMessage,
    refetch: fetchMessages,
  };
}

export function useLatestMessages(sessionId: string, limit: number = 10) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchLatestMessages = async () => {
    if (!sessionId) return;
    
    try {
      setLoading(true);
      setError(null);
      const response = await messageApi.getLatestMessages(sessionId, limit);
      setMessages(response);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to get latest messages');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLatestMessages();
  }, [sessionId, limit]);

  return {
    messages,
    loading,
    error,
    refetch: fetchLatestMessages,
  };
}
